package com.it.jwt.handler;

import com.it.common.utils.RedisCache;
import com.it.common.utils.Response;
import com.it.jwt.utils.JwtTokenHelper;
import com.it.jwt.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class LogoutStatusSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private RedisCache redisCache;

    @Value("${jwt.tokenPrefix}")
    private String tokenPrefix;

    @Value("${jwt.tokenHeaderKey}")
    private String tokenHeaderKey;


    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String header = request.getHeader(tokenHeaderKey);
        // 判断 value 值是否以 Bearer 开头
        if (StringUtils.startsWith(header, tokenPrefix)) {
            // 截取 Token 令牌
            String token = StringUtils.substring(header, 7);
            log.info("Token: {}", token);
            // 判空 Token
            if (StringUtils.isNotBlank(token)) {
                String key = "login:token"+token;
                // 从 Token 中解析出用户名
                redisCache.deleteObject(key);
            }
        }
        ResultUtil.ok(response, Response.success());
    }
}
